/*
 *  Copyright (C) 2004 Cidero, Inc.
 *
 *  Permission is hereby granted to any person obtaining a copy of 
 *  this software to use, copy, modify, merge, publish, and distribute
 *  the software for any non-commercial purpose, subject to the
 *  following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY IN CONNECTION WITH THE SOFTWARE.
 * 
 *  File: $RCSfile: ATronDeviceManager.java,v $
 *
 */

package com.cidero.bridge.audiotron;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import org.cybergarage.upnp.device.InvalidDescriptionException;

import com.cidero.bridge.BridgeDeviceManager;
import com.cidero.util.MrUtil;
import com.cidero.util.AppPreferences;

/**
 * This singleton class handles the management of multiple 
 * ATronMediaRenderer 'bridge' device instances.
 * The real work with regard to the translation of UPnP commands 
 * to their Audiotron HTTP-based equivalents is done in the 
 * ATronMediaRenderer class
 * 
 */
public class ATronDeviceManager implements BridgeDeviceManager
{
  private static Logger logger = 
     Logger.getLogger("com.cidero.bridge.audiotron");

  private final static int AUDIOTRON_MAX_UNITS = 10;

  List   activeDeviceList = new ArrayList();

  static AppPreferences pref;

  
  public ATronDeviceManager()
  {
    loadPreferences();

    instantiateDeviceBridges();
  }
  
  /*
   *  Load Audiotron property file. File contains list of audiotron 
   *  IP addresses and logical names. 
   */
  public static void loadPreferences()
  {
    // Load shared & user-specific preferences for this application
    pref = new AppPreferences(".cidero");

    if( ! pref.load( "Bridge", "ATronDeviceManager" ) )
    {
      logger.severe("Missing preferences file - exiting");
      System.exit(-1);
    }
  }

  public void savePreferences()
  {
    pref.saveUserPreferences( "Bridge", "ATronDeviceManager" );
  }

  public static AppPreferences getPreferences()
  {
    if( pref == null )
      loadPreferences();
    
    return pref;
  }

  /** 
   *  Instantiate a bridge device for each AudioTron specified in the 
   *  preferences file. 
   */
  public void instantiateDeviceBridges()
  {
    logger.fine("Entering instantiateDeviceBridges " );

    for( int n = 1 ; n <= AUDIOTRON_MAX_UNITS ; n++ )
    {
      String propPrefix = "audiotron" + n + "_";
      
      String enabled = pref.get( propPrefix + "enabled" );
      if( (enabled == null) || (! enabled.equals("true")) ) 
        continue;
      
      String ipAddr = pref.get( propPrefix + "ipaddr" );
      String deviceName = pref.get( propPrefix + "name" );

      // GoAhead Web server on Audiotron requires username/password
      String userName = pref.get( propPrefix + "userName" );
      String password = pref.get( propPrefix + "password" );
      if( userName == null )
        userName = "";
      if( password == null )
        password = "admin";

      if( deviceName == null || ipAddr == null )
      {
        logger.warning("ATronDeviceManager: missing device name or ipaddr" );
        continue;
      }
      
      logger.info("Starting Audiotron UPnP bridge for device '" + 
                  deviceName + "' at ipAddr " + ipAddr );

      logger.info(" username: " + userName + " password: " + password );

      try 
      {
        ATronMediaRenderer bridgeDev = 
          new ATronMediaRenderer( ipAddr, deviceName, 
                                  userName, password );

        activeDeviceList.add( bridgeDev );

        logger.info("Starting Audiotron media renderer");
        bridgeDev.start();
      }
      catch( InvalidDescriptionException e )
      {
        logger.severe("ATronDeviceManager: Invalid UPnP device description" );
      }
    }

    logger.fine("Leaving getProperties " );
  }

  public void start()
  {
    logger.fine("Starting AudiotronDeviceManager " );


    // TODO: If device supports it, start thread that monitors Audiotron 
    // & detects timeouts etc...
    //AudiotronDeviceMonitor monitor = 
    //       new AudioTronDeviceMonitor( this )
    //monitor.start();
  }

  public void stop()
  {
    logger.fine("Stopping ATronDeviceManager " );

    for( int n = 0 ; n < activeDeviceList.size(); n++ )
    {
      ATronMediaRenderer bridgeDev = 
         (ATronMediaRenderer)activeDeviceList.get(n);
      bridgeDev.stop();
    }
  }


  public static void main(String args[])
  {
    ATronDeviceManager devManager = new ATronDeviceManager();

    devManager.start();
  }
  

}

